package nasif.cn.imagewikis.web.controller.api;

import java.util.List;

import javax.annotation.Resource;

import nasif.cn.imagewikis.ao.api.PictureHttpApiService;
import nasif.cn.imagewikis.common.utils.DESUtil;
import nasif.cn.imagewikis.entity.Picture;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/api")
public class PictureHttpApiCRUD {
	@Resource
	protected PictureHttpApiService pictureHttpApiService;

	@RequestMapping(value = "/picture/get", method = RequestMethod.GET)
	public @ResponseBody String  sample(Integer pageNo) {
		if (pageNo == null)
			pageNo = 1;
		List<Picture> list = pictureHttpApiService.getPageNo(pageNo);
		JSONArray jsonArray = new JSONArray();
		for (Picture picture : list) {
			JSONObject jsonObject = JSONObject.fromObject(picture);
			jsonArray.add(jsonObject);
		}
		String ret = jsonArray.toString();
		return ret;
	}

	@RequestMapping(value = "/picture/add", method = RequestMethod.POST)
	public @ResponseBody
	void add(String url, String detailUrl, String description, String hex) {
		Picture picture = new Picture();
		if (hex != null && hex.equals("true")) {
			try {
				description = new String(DESUtil.hex2byte(description));
			} catch (IllegalArgumentException e) {
			}
		}
		picture.setDescription(description);
		picture.setUrl(url);
		picture.setDetailUrl(detailUrl);
		pictureHttpApiService.add(picture);
	}
}
